<template>
  <div class="department-manage">
    <el-card shadow="hover">
      <div class="header">
        <el-input
          v-model="searchText"
          placeholder="搜索设备/部门"
          clearable
          style="width:240px;margin-right:16px;"
          @keyup.enter="doSearch"
        />
        <el-select v-model="searchDept" placeholder="部门" clearable style="width:140px;margin-right:16px;">
          <el-option v-for="item in deptOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-button type="primary" @click="handleAdd">新增分配</el-button>
      </div>
      <el-table :data="filteredList" border style="margin-top:16px;">
        <el-table-column prop="id" label="编号" width="100px" align="center"/>
        <el-table-column prop="name" label="设备名称" width="180px"/>
        <el-table-column prop="type" label="设备类型" width="180px"/>
        <el-table-column prop="department" label="归属部门" width="180px"/>
        <el-table-column prop="manager" label="负责人" width="180px"/>
        <el-table-column label="操作" width="250px" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" text @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="warning" text @click="showHistory(scope.row)">分配历史</el-button>
            <el-button size="small" type="danger" text @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑分配弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="440px" destroy-on-close>
      <el-form :model="editRow" :rules="formRules" ref="formRef" label-width="90px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="editRow.name" />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="editRow.type" placeholder="请选择">
            <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门" prop="department">
          <el-select v-model="editRow.department" placeholder="请选择">
            <el-option v-for="item in deptOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="editRow.manager" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog v-model="deleteVisible" title="提示" width="320px" center>
      <div>确定要删除该分配记录吗？</div>
      <template #footer>
        <el-button @click="deleteVisible=false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配历史弹窗 -->
    <el-dialog v-model="historyVisible" title="分配历史" width="480px" center>
      <el-table :data="historyList" border>
        <el-table-column prop="date" label="日期" width="120"/>
        <el-table-column prop="department" label="分配部门"/>
        <el-table-column prop="manager" label="负责人"/>
      </el-table>
      <template #footer>
        <el-button type="primary" @click="historyVisible=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 类型定义
interface AssignItem {
  id: number
  name: string
  type: string
  department: string
  manager: string
  history: { date: string, department: string, manager: string }[]
}
const typeOptions = ['空调主机', '空气净化器', '电梯', '照明系统', '水泵', '配电柜']
const deptOptions = ['工程部', '后勤部', '物业部']

// 模拟分配数据
const assignList = ref<AssignItem[]>([
  {
    id: 1001, name: '中央空调1', type: '空调主机', department: '工程部', manager: '张三',
    history: [
      { date: '2024-01-05', department: '工程部', manager: '张三' },
      { date: '2023-07-01', department: '物业部', manager: '王五' }
    ]
  },
  {
    id: 1002, name: '新风主机2', type: '空气净化器', department: '后勤部', manager: '李四',
    history: [
      { date: '2024-01-10', department: '后勤部', manager: '李四' }
    ]
  },
  {
    id: 1003, name: '电梯3', type: '电梯', department: '物业部', manager: '王五',
    history: [
      { date: '2023-11-18', department: '物业部', manager: '王五' },
      { date: '2023-03-02', department: '后勤部', manager: '李四' }
    ]
  },
  {
    id: 1004, name: '消防泵4', type: '水泵', department: '工程部', manager: '张三',
    history: [
      { date: '2024-03-15', department: '工程部', manager: '张三' }
    ]
  },
  {
    id: 1005, name: '配电柜5', type: '配电柜', department: '后勤部', manager: '李四',
    history: [
      { date: '2023-10-21', department: '后勤部', manager: '李四' }
    ]
  },
  {
    id: 1006, name: '净水设备6', type: '空气净化器', department: '工程部', manager: '张三',
    history: [
      { date: '2024-02-28', department: '工程部', manager: '张三' }
    ]
  },
  {
    id: 1007, name: '照明系统7', type: '照明系统', department: '物业部', manager: '王五',
    history: [
      { date: '2023-12-12', department: '物业部', manager: '王五' }
    ]
  },
  {
    id: 1008, name: '中央空调8', type: '空调主机', department: '后勤部', manager: '李四',
    history: [
      { date: '2024-04-10', department: '后勤部', manager: '李四' }
    ]
  },
  {
    id: 1009, name: '新风主机9', type: '空气净化器', department: '工程部', manager: '张三',
    history: [
      { date: '2024-05-01', department: '工程部', manager: '张三' }
    ]
  },
  {
    id: 1010, name: '配电柜10', type: '配电柜', department: '物业部', manager: '王五',
    history: [
      { date: '2023-08-23', department: '物业部', manager: '王五' }
    ]
  }
])


// 搜索
const searchText = ref('')
const searchDept = ref('')
const filteredList = computed(() => {
  let arr = assignList.value
  if (searchText.value) {
    arr = arr.filter(
      r =>
        r.name.includes(searchText.value) ||
        r.department.includes(searchText.value)
    )
  }
  if (searchDept.value) {
    arr = arr.filter(r => r.department === searchDept.value)
  }
  return arr
})
function doSearch() {}

// 新增/编辑弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增分配')
const editRow = reactive<AssignItem>({
  id: 0,
  name: '',
  type: '',
  department: '',
  manager: '',
  history: []
})
const formRef = ref()
const formRules = {
  name: [{ required: true, message: '必填', trigger: 'blur' }],
  type: [{ required: true, message: '必选', trigger: 'change' }],
  department: [{ required: true, message: '必选', trigger: 'change' }],
  manager: [{ required: true, message: '必填', trigger: 'blur' }]
}
function handleAdd() {
  dialogTitle.value = '新增分配'
  Object.assign(editRow, { id: 0, name: '', type: '', department: '', manager: '', history: [] })
  dialogVisible.value = true
}
function handleEdit(row: AssignItem) {
  dialogTitle.value = '编辑分配'
  Object.assign(editRow, row)
  dialogVisible.value = true
}
function submitEdit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return
    if (dialogTitle.value.startsWith('编辑')) {
      const idx = assignList.value.findIndex(t => t.id === editRow.id)
      if (idx !== -1) {
        // 历史记录加一条
        assignList.value[idx].history.unshift({
          date: new Date().toISOString().slice(0,10),
          department: editRow.department,
          manager: editRow.manager
        })
        assignList.value[idx] = { ...editRow, history: assignList.value[idx].history }
      }
      ElMessage.success('编辑成功')
    } else {
      editRow.id = assignList.value.length ? Math.max(...assignList.value.map(r => r.id)) + 1 : 1001
      editRow.history = [
        { date: new Date().toISOString().slice(0,10), department: editRow.department, manager: editRow.manager }
      ]
      assignList.value.unshift({ ...editRow })
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
  })
}

// 删除
const deleteVisible = ref(false)
const deleteTarget = ref<AssignItem | null>(null)
function handleDelete(row: AssignItem) {
  deleteTarget.value = row
  deleteVisible.value = true
}
function confirmDelete() {
  if (deleteTarget.value) {
    assignList.value = assignList.value.filter(t => t.id !== deleteTarget.value!.id)
    ElMessage.success('删除成功')
  }
  deleteVisible.value = false
}

// 分配历史弹窗
const historyVisible = ref(false)
const historyList = ref<{ date: string, department: string, manager: string }[]>([])
function showHistory(row: AssignItem) {
  historyList.value = row.history
  historyVisible.value = true
}
</script>

<style scoped>
.department-manage {
  width: 1400px;
  margin: 0 auto;
  padding: 12px 0;
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
</style>
